<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :search.sync="query"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择工单号" :disabled="true" v-model="query.workOrderNo" clearable>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="
              openCommonModal({
                type: 'queryWorkOrderModal'
              })
            "
          ></el-button>
        </el-input>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" v-if="permission.outInfoBind_bind" @click="handleBindInfo">绑定</el-button>
        <el-button type="danger" size="small" v-if="permission.outInfoBind_unbind" @click="handleUnbindInfo" :disabled="!selectionList.length">解绑</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <el-dialog title="绑定" :visible.sync="dialogVisible" top="3vh" width="60%" append-to-body destroy-on-close :close-on-press-escape="false">
      <avue-form :option="formOption" v-model="bindForm" ref="bindForm" @submit="handleSubmit"> </avue-form>
      <avue-crud :option="bindOption" :data="bindData" @row-del="rowDel" ref="bindCrud">
        <template slot="menuLeft">
          <span class="title"> <span class="el-icon-vertical-bar"></span>已扫描数据 </span>
        </template>
        <template slot="menuRight">
          <span class="title">共{{ bindLength }}项</span>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="$refs.bindForm.submit()">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { bind, unbind, getList, getPackNum } from '@/api/product/outInfoBind';

export default {
  name: 'outInfoBind', // 会渲染成传入的componentName
  components: {
    userTableConfig,
    GlobalModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      visibile: false,
      timer: new Date().getTime(),
      tableOption: {},
      query: {},
      bindForm: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      formOption: {
        emptyBtn: false,
        submitBtn: false,
        detail: false,
        labelWidth: 160,
        group: [
          {
            label: '',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 120,
            display: true,
            // icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '工单号',
                prop: 'workOrderNo',
                disabled: true,
                span: 12,
                type: 'search',
                appendClick: () => {
                  this.openCommonModal({
                    type: 'editWorkOrderModal'
                  });
                },
                rules: [
                  {
                    required: true,
                    message: '请选择工单号',
                    trigger: 'change'
                  }
                ]
              }
            ]
          },
          {
            label: '绑定设置',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 120,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '源数据类型',
                prop: 'referenceSource',
                span: 12,
                type: 'select',
                dicData: [
                  { label: '原材料', value: 'MATERIAL' },
                  { label: '工单信息', value: 'WORKORDER_INFO' },
                  { label: '生产信息', value: 'PRODUCTION_INFO' }
                ],
                rules: [
                  {
                    required: true,
                    message: '请选择源数据类型',
                    trigger: 'change'
                  }
                ]
              },
              {
                label: '绑定数据类型',
                prop: 'referenceLabel',
                span: 12,
                type: 'select',
                dicData: [
                  { label: '包装条码', value: 'PACKING_SN' },
                  { label: '产品序列号', value: 'PRODUCT_SN' }
                ],
                rules: [
                  {
                    required: true,
                    message: '请选择绑定数据类型',
                    trigger: 'change'
                  }
                ]
              }
            ]
          },
          {
            label: '操作区',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 120,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '源数据',
                prop: 'referenceKey',
                span: 12,
                enter: async (val) => {
                  if (val) {
                    const res = await getPackNum({ sequenceNumber: val });
                    const data = res.data.data;
                    if (data && Object.keys(data).length && data.vendorLotNo) {
                      this.bindForm.referenceKey = data.vendorLotNo;
                    }
                  }
                }
              },
              {
                label: '绑定数据',
                prop: 'referenceValue',
                span: 12,
                enter: (val) => {
                  if (val && this.bindForm.referenceKey) {
                    this.bindData.push({ referenceValue: val, referenceKey: this.bindForm.referenceKey });
                    this.bindForm.referenceValue = '';
                    this.$refs.bindForm.$refs.referenceValue.focus();
                  } else {
                    this.$message.warning('请检查源数据和绑定数据是否填写正确');
                  }
                }
              }
            ]
          }
        ]
      },
      modalName: {},
      dialogVisible: false,
      selectionList: [],
      data: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menu: false,
        selection: true,
        columnBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 1
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partNo'
          },
          {
            label: '源数据类型',
            prop: 'referenceSource',
            type: 'select',
            dicData: [
              { label: '原材料', value: 'MATERIAL' },
              { label: '工单信息', value: 'WORKORDER_INFO' },
              { label: '生产信息', value: 'PRODUCTION_INFO' }
            ]
          },
          {
            label: '源数据',
            prop: 'referenceKey',
            search: true
          },
          {
            label: '绑定数据类型',
            prop: 'referenceLabel',
            type: 'select',
            dicData: [
              { label: '包装条码', value: 'PACKING_SN' },
              { label: '产品序列号', value: 'PRODUCT_SN' }
            ]
          },
          {
            label: '绑定数据',
            prop: 'referenceValue',
            search: true
          },
          {
            label: '绑定人',
            prop: 'createUserName'
          },
          {
            label: '绑定时间',
            prop: 'createTime'
          },
          {
            label: '数据来源',
            prop: 'referenceType',
            type: 'select',
            dicData: [
              { label: '工站作业', value: 'STATION_OPERATION' },
              { label: '追溯绑定', value: 'TRACING_BINDING' }
            ]
          }
        ]
      },
      bindOption: {
        height: 300,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        refreshBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        addBtn: false,
        menu: true,
        selection: false,
        columnBtn: false,
        column: [
          {
            label: '源数据',
            prop: 'referenceKey'
          },
          {
            label: '绑定数据',
            prop: 'referenceValue'
          }
        ]
      },
      bindData: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      return this.selectionList.map((el) => el.id);
      // return ids.join(',');
    },
    bindLength() {
      return this.bindData.length;
    }
  },
  methods: {
    selectionChange(list) {
      this.selectionList = list;
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done(row);
      });
    },

    beforeOpen(done, type) {},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = Object.assign(this.query, params);
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      try {
        this.loading = true;
        const res = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.selectionClear();
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    openCommonModal(params) {
      let { type } = params;
      this.modalName = type;
      this.visibile = true;
      this.tableOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90,
        templateName: 'WORKORDER'
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'queryWorkOrderModal':
          // this.query.workOrderNo = this._get(rowData, 'orderNo', '');
          // this.query.workOrderId = this._get(rowData, 'id', '');
          this.$set(this.query, 'workOrderNo', this._get(rowData, 'orderNo', ''));
          this.$set(this.query, 'workOrderId', this._get(rowData, 'id', ''));
          break;
        case 'editWorkOrderModal':
          this.bindForm.workOrderNo = this._get(rowData, 'orderNo', '');
          this.bindForm.workOrderId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    handleUnbindInfo() {
      this.$confirm('确定将选择数据解绑?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await unbind(this.ids);
        this.$message.success('解绑成功');
        this.onLoad(this.page);
      });
    },
    handleBindInfo() {
      this.dialogVisible = true;
    },
    handleCancel() {
      this.bindData = [];
      this.$refs.bindForm.resetForm();
      this.dialogVisible = false;
    },
    async handleSubmit(form, done) {
      if (!this.bindData.length) {
        this.$message.warning('请录入扫描数据');
        done();
      } else {
        try {
          const data = {
            bindingDTOs: this.bindData,
            ...form
          };
          const res = await bind(data);
          this.$message.success('绑定成功');
          this.$refs.bindForm.resetForm();
          this.bindData = [];
          this.dialogVisible = false;
          this.onLoad(this.page);
        } catch (e) {
        } finally {
          done();
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: 600;
}
</style>
